import 'package:get/get.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/xindong_chat_singleton.dart';
import 'package:xindong/manager/xindong_database_singleton.dart';
import 'package:xindong/manager/xindong_page_singleton.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/models/user/xindong_user.dart';

class XinDongSayHelloClass {
  int id = 0;
  int updateAt = 0;
  String userId = "0";
  String targetUid = "0";

  XinDongSayHelloClass();

  // Json转Class
  factory XinDongSayHelloClass.fromJson(Map<String, dynamic> json) {
    return XinDongSayHelloClass()
      ..id = json["id"]
      ..userId = json["user_id"]
      ..targetUid = json["target_uid"]
      ..updateAt = json["update_at"];
  }
}

// 搭讪
class XinDongHelloCtr extends GetxController {
  static XinDongHelloCtr get to => Get.find();

  List<XinDongSayHelloClass> dataList = [];

  // 打招呼过期时间(秒)
  int get expiredTime => 24 * 60 * 60; // 24小时

  // 打招呼过期时间文本
  String get formatHiLimitTimeText {
    if (expiredTime >= 60 * 60 * 24) {
      return "${(expiredTime / (60 * 60 * 24)).ceil()}天";
    } else if (expiredTime >= 60 * 60) {
      return "${(expiredTime / (60 * 60)).ceil()}小时";
    } else if (expiredTime >= 60) {
      return "${(expiredTime / 60).ceil()}分钟";
    } else {
      return "$expiredTime秒";
    }
  }

  // 登录用户ID（每个用户都有自己的记录）
  String get loginUserId {
    return XinDongUserController.to.loginId ?? "0";
  }

  // 手机时间戳(秒)
  int get timestamp => DateTime.now().millisecondsSinceEpoch ~/ 1000;

  // 过期时间差
  int get expiredTimeDifference => timestamp - expiredTime;

  // 需要登录
  Future afterLoginSetup() async {
    await deleteExpiredData();
    final result = await XinDongDatabaseSingleton.instance.htmy_querySayHelloWithUserId(loginUserId);
    dataList = result.map((e) => XinDongSayHelloClass.fromJson(e)).toList();
    return Future.value();
  }

  Future getData() async {
    final result = await XinDongDatabaseSingleton.instance.htmy_querySayHelloWithUserId(loginUserId);
    dataList = result.map((e) => XinDongSayHelloClass.fromJson(e)).toList();
    return dataList;
  }

  // 删除过期数据
  deleteExpiredData() async {
    return await XinDongDatabaseSingleton.instance.htmy_deleteSayHelloExpired(expiredTime: expiredTimeDifference);
  }

  // 插入或更新数据
  updateSaveData({required String targetUid, required int updateAt}) async {
    final result = await XinDongDatabaseSingleton.instance.htmy_insertSayHello(
      userId: loginUserId,
      targetUid: targetUid,
      updateAt: updateAt,
    );
    if (result > 0) {
      dataList.insert(
        0,
        XinDongSayHelloClass()
          ..id = result
          ..userId = loginUserId
          ..targetUid = targetUid
          ..updateAt = updateAt,
      );
    }
  }

  // 插入或更新数据
  void updateSaveListData({required List<String> targetIds, required int updateAt}) async {
    await XinDongDatabaseSingleton.instance.htmy_insertMultipleSayHello(
      userId: loginUserId,
      targetIds: targetIds,
      updateAt: updateAt,
    );
  }

  // 匹配数据
  Future<List> matchGreetData(List userList) async {
    userList.forEach((element) => element.canSayHello = true);
    dataList = await getData();
    if (dataList.isEmpty) {
      return userList;
    }
    for (var user in userList) {
      user = matchUserGreetData(user, timestamp);
    }
    return userList;
  }

  // 单个用户数据匹配
  XinDongUser matchUserGreetData(XinDongUser userClass, int timestamp) {
    XinDongSayHelloClass sayHelloClass = dataList.firstWhere(
      (element) => element.targetUid == userClass.uid,
      orElse: () => XinDongSayHelloClass(),
    );
    if (sayHelloClass.id != 0) {
      userClass.sayHelloTime = sayHelloClass.updateAt;
      if (sayHelloClass.updateAt > timestamp - expiredTime) {
        userClass.canSayHello = false;
      }
    }
    return userClass;
  }

  /// 点击用户打招呼
  ///
  /// model 用户模型
  /// needJumpToChat 需要跳到聊天页
  Future<void> onSayHelloUser(XinDongUser model, {bool free = false, bool needJumpToChat = true}) async {
    try {
      mDebugPrint("打招呼数据 $dataList $timestamp");
      model.canSayHello = true;
      model = matchUserGreetData(model, timestamp);
      if (model.canSayHello == true) {
        bool result = await XinDongChatSingleton.instance.sayHello(user: model, free: free);
        if (result) {
          model.canSayHello = false;
          model.sayHelloTime = timestamp;
          // 通知单个更新（避免全局刷新耗性能）
          update([model.uid]);
          updateSaveData(targetUid: model.uid, updateAt: timestamp);
          mDebugPrint("当前打招呼数据 $dataList");
          if (needJumpToChat) {
            showToast("已发送");
          }
        }
      } else {
        // 通知单个更新（避免全局刷新耗性能）
        update([model.uid]);
        if (needJumpToChat) {
          XinDongPageSingleton.instance.jumpToChatYeMian(userClass: model);
        }
      }
    } catch (error) {
      mCatchPrint(error);
    } finally {}
    return Future.value();
  }
}
